package com.cloudservice.ccs.config;

import com.cloudservice.ccs.entity.CustomerService;
import com.cloudservice.ccs.mapper.CustomerServiceMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

public class CustomerServiceRealm extends AuthorizingRealm {

    @Autowired
    private CustomerServiceMapper customerServiceMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> permissionSet = new HashSet<>();
        permissionSet.add("all");
        authorizationInfo.setStringPermissions(permissionSet);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String email = (String) authenticationToken.getPrincipal();
        if (email == null || email.isEmpty()) {
            throw new UnknownAccountException("未知用户");
        }
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("email", email);
        List<CustomerService> foundCustomerServices = customerServiceMapper.getWithConditions(conditions);
        if (foundCustomerServices == null || foundCustomerServices.isEmpty()) {
            throw new UnknownAccountException("用户不存在");
        }
        CustomerService foundCustomerService = foundCustomerServices.get(0);
        return new SimpleAuthenticationInfo(foundCustomerService.getCustomerServiceId(), foundCustomerService.getPassword(), getName());
    }
}
